const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');

// 获取班级列表
router.get('/', async (req, res) => {
  try {
    console.log('获取班级列表请求，参数:', req.query);
    const department = req.query.department;
    
    let query = 'SELECT id, className as name, department, grade FROM classes';
    let params = [];
    
    // 如果提供了院系参数，则按院系筛选
    if (department) {
      query += ' WHERE department = ?';
      params.push(department);
    }
    
    const [rows] = await pool.query(query, params);
    console.log('返回班级列表:', rows);
    
    res.json(rows);
  } catch (error) {
    console.error('获取班级列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});
// 获取班级详情
router.get('/:id', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM classes WHERE id = ?', [req.params.id]);
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '班级不存在' });
    }
    
    res.json(rows[0]);
  } catch (error) {
    console.error('获取班级详情失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router;